<?php
/**
 * Created by PhpStorm.
 * User: DongYao
 * Date: 2017/11/28
 * Time: 下午2:22
 */

namespace XmtApp\Modules\Admin\Controllers\Api;


use App\Exceptions\ApiException;
use App\Http\Requests\AgentPost;
use App\Http\Resources\UserResource;
use App\Http\Resources\UsersResource;
use App\Http\Resources\UserAgentExtendResource;
use App\Tables\Role;
use App\Tables\User;
use App\Tables\UserAgentExtend;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use XmtApp\Modules\Admin\Controllers\Controller;
use DB;

class AgentController extends Controller
{
    public $user;

    public function __construct()
    {
        parent::__construct();

        $this->user = Auth::guard('api')->user();
    }

    /**
     * 查询代理用户列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        if ($this->user->hasRole('agent') && $this->user->extension->agent_level == 3) {
            abort(403);
        }

        $query = new User();
        $query = $query->agents();

        /**
         * 设置查询条件
         */
        if ($request->filled('province_code')) {
            $query = $query->where('province_code', $request->province_code);
        }

        if ($request->filled('city_code')) {
            $query = $query->where('city_code', $request->city_code);
        }

        if ($request->filled('district_code')) {
            $query = $query->where('district_code', $request->district_code);
        }

        if ($request->filled('created_at') && is_array($request->created_at)) {
            $query = $query->whereBetween('created_at', $request->created_at);
        }

        if ($request->filled('agent_level')) {
            $query = $query->whereHas('extension', function ($query) use ($request) {
                $query->where('agent_level', $request->agent_level);
            });
        }

        if ($request->filled('audit_status')) {
            $query = $query->whereHas('extension', function ($query) use ($request) {
                $query->where('audit_status', $request->audit_status);
            });
        }

        if ($request->filled('keyword')) {
            $query = $query->where(function($query) use ($request) {
                $query->orWhere('name', 'like', "%{$request->keyword}%");
                $query->orWhere('realname', 'like', "%{$request->keyword}%");
                $query->orWhere('nickname', 'like', "%{$request->keyword}%");
            });
        }

        if ($this->user->hasRole('agent')) {
            if ($this->user->extension->agent_level == 1) {
                $query = $query->ofChildren($this->user->id);
            } else if ($this->user->extension->agent_level == 2) {
                $query = $query->whereHas('extension', function ($query) {
                    $query->where('parent_user_id', $this->user->id);
                });
            }
        }

        // 级联查询下级代理
        if ($request->filled('parent_agent_id')) {
            $query = $query->ofChildren($request->parent_agent_id);
        } else {
            if (!$this->user->hasRole('system') && !$this->user->hasRole('admin')) {
                $query = $query->ofChildren($this->user->id);
            }
        }

        $query = $query->orderBy('created_at', 'desc');

        $data = $query->paginate($request->header('pageSize'));

        return new UsersResource($data);
    }

    /**
     * 添加代理用户
     * @param AgentPost $request
     * @return \Illuminate\Http\JsonResponse
     * @throws ApiException
     */
    public function add(AgentPost $request)
    {
        $main_data = $request->all([
            'name', 'password', 'sex', 'is_effect', 'source', 'email', 'identity_card', 'realname', 'mobile',
            'province_code', 'city_code', 'district_code', 'address'
        ]);

        if ($this->user->hasRole('agent') && $this->user->extension->agent_level == 3) {
            throw new ApiException('3级代理用户不可以添加下级代理');
        }

        $agent = new User($main_data);
        DB::transaction(function () use ($main_data, &$agent, $request) {
            /**
             * 添加代理基础信息
             */
            $agent->password = bcrypt($main_data['password']);
            $agent->type = 1;
            if (!$agent->save()) {
                throw new ApiException('添加代理基础信息失败');
            }

            $role = Role::where('name', 'agent')->first();
            if (empty($role)) {
                throw new ApiException('请先添加代理角色');
            }
            $agent->attachRole($role);

            /**
             * 添加代理扩展信息
             */
            $agent_extend = new UserAgentExtend();
            $agent_extend->user_id = $agent->id;

            if ($this->user->hasRole('admin') || $this->user->hasRole('system')) { // 只有管理员可添加一级代理
                $agent_extend->audit_status = 'approved';
                $agent_extend->agent_level= 1;
                $agent_extend->parent_user_id = 0;

                /**
                 * 代理级别分红key
                 */
                $level_key = 'v' . $agent_extend->agent_level;
                $agent_extend->proration = $request->prorations[$level_key];
                $agent_extend->prorations = $request->prorations;

            } else if ($this->user->hasRole('agent')) { // 代理用户可添加自己的下级代理用户
                $agent_extend->audit_status = 'wait_audit';
                $agent_extend->agent_level = $this->user->extension->agent_level + 1;
                $agent_extend->parent_user_id = $this->user->id;
                /**
                 * 代理级别分红key
                 */
                $level_key = 'v' . $agent_extend->agent_level;
                $agent_extend->proration = $this->user->extension->prorations[$level_key];
                $agent_extend->prorations = $this->user->extension->prorations;
            }

            $agent_extend->operation_user_id = $this->user->id;

            if(!$agent_extend->save()) {
                throw new ApiException('添加代理扩展信息失败');
            }
        }, 3);

        return response()->json(ajax_return(true, '添加成功', new UserResource($agent)));
    }

    /**
     * 修改代理用户信息
     * @param $id
     * @param AgentPost|Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws ApiException
     */
    public function update($id, AgentPost $request)
    {
        $main_data = $request->all([
            'name', 'realname', 'sex', 'email', 'identity_card',
            'province_code', 'city_code', 'district_code', 'address'
        ]);

        $agent = User::find($id);

        if (empty($agent)) {
            throw new ApiException('代理信息不存在');
        }

        if ($this->user->hasRole('agent') && $agent->parent_id != $this->user->id) {
            throw new ApiException('您不是该代理的直接上级代理，不能修改');
        }

        DB::transaction(function () use ($main_data, &$agent, $request) {
            /**
             * 修改代理基础信息
             */
            if ($request->filled('password')) {
                $agent->password = bcrypt($request->password);
            }

            if (!$agent->update($main_data)) {
                throw new ApiException('修改代理基础信息失败');
            }

            /**
             * 添加代理扩展信息
             */
            $agent_extend = UserAgentExtend::where('user_id', $agent->id)->first();
            if (empty($agent_extend)) {
                throw new ApiException('代理扩展信息不存在, 修改失败');
            }

            /**
             * 代理级别分红key
             */
            $level_key = 'v' . $agent_extend->agent_level;
            $agent_extend->proration = $request->proration;
            $agent_extend->prorations = $request->prorations;

            if(!$agent_extend->save()) {
                throw new ApiException('修改代理扩展信息失败');
            }
        }, 3);

        return response()->json(ajax_return(true, '修改成功', new UserResource($agent)));
    }

    /**
     * 代理商审核-拒绝通过
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function reject($id)
    {
        $agent = UserAgentExtend::where('user_id', $id)->first();
        if (empty($agent)) {
            return response()->json(ajax_return(false, '代理商信息不存在'));
        }
        $agent->audit_status = 'rejection';

        $res = $agent->save();
        if ($res) {
            return response()->json(ajax_return(true, '操作成功', new UserAgentExtendResource($agent)));
        } else {
            return response()->json(ajax_return(false, '操作失败'));
        }
    }

    /**
     * 代理商审核-通过审核
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function pass($id)
    {
        $agent = UserAgentExtend::where('user_id', $id)->first();
        if (empty($agent)) {
            return response()->json(ajax_return(false, '代理商信息不存在'));
        }
        $agent->audit_status = 'approved';

        $res = $agent->save();
        if ($res) {
            return response()->json(ajax_return(true, '操作成功', new UserAgentExtendResource($agent)));
        } else {
            return response()->json(ajax_return(false, '操作失败'));
        }
    }

    /**
     * 设置代理账户是否有效
     * @param $id
     * @param $status
     * @return \Illuminate\Http\JsonResponse
     * @throws ApiException
     * @internal param UserPost $request
     */
    public function toggleStatus($id, $status)
    {
        $agent = User::find($id);

        /**
         * 判断是否有修改此代理的权限
         */
        if ($this->user->hasRole('agent') && $this->user->id != $id) {
            if ($agent->extension->parent_user_id != $this->user->id) {
                throw new ApiException('你不能修改此代理信息，这不是你的下级代理');
            }
        }
        $agent->is_effect = $status;

        $res = $agent->save();
        if ($res) {
            return response()->json(ajax_return(true, '设置成功'));
        } else {
            return response()->json(ajax_return(false, '设置失败'));
        }
    }

    /**
     * 级联获取代理名称
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function names(Request $request)
    {
        // 获取查询的代理级别
        $level = $request->get('level', 1);
        // 当前代理级别
        $agent_level = 0;

        if (!empty($this->user) && $this->user->hasRole('agent')) {
            $agent_level = $this->user->extension->agent_level;
        }

        $query = User::agents();

        /**
         * 限制代理数据
         */
        if (!empty($this->user) && $this->user->hasRole('agent')) {
            if ($agent_level == $level) {
                $query = $query->where('id', $this->user->id);
            }
        }

        $query = $query->whereHas('extension', function ($query) use ($request, $level, $agent_level) {

            $query->where('agent_level', $level);

            if ($level == 1) {
                if (!empty($this->user) && $this->user->hasRole('agent')) {
                    if ($agent_level == 1) {
                        $query->where('user_id', $this->user->id);
                    } else if ($agent_level == 2) {
                        $query->where('user_id', $this->user->extension->parent_user_id);
                    } else if ($agent_level == 3) {
                        $query->where('user_id', $this->user->extension->parent->extension->parent_user_id);
                    }
                }
            }  else if ($level == 2) {
                if (!empty($this->user) && $this->user->hasRole('agent')) {
                     if ($agent_level == 3) {
                        $query->where('user_id', $this->user->extension->parent_user_id);
                     }
                }
                $query->where('parent_user_id', $request->get('parent_id', ''));
            } else {
                $query->where('parent_user_id', $request->get('parent_id', ''));
            }

            if ($request->filled('keyword')) {
                $query->where(function ($query) use ($request) {
                    $query->orWhere('name', 'like', "%{$request->keyword}%");
                    $query->orWhere('realname', 'like', "%{$request->keyword}%");
                });
            }
        });

        $data = $query->limit(100)->get();


        $data = array_map(function ($item) {
            return ['id' => $item['id'], 'name' => $item['name'], 'realname' => $item['realname'], 'level' => $item['extension']['agent_level']];
        }, $data->toArray());

        return response()->json(ajax_return(true, 'ok', $data));
    }
}